const schedule = require('node-schedule');
const db = require('../../db');
const {get_blood_war_info_async,history_hash_table,save_blood_war_info} = require('../dao/redis_dao');
const {formatLocalTimeYYMMDD} = require('../../utils/date');
const {rankRewardDailyMap, rankRewardMonthMap, dailyGiveMap, ironWarHurtMap} = require('../config/commonConfig');


//渠道任务结束将已发奖励的变为历史的
async function channelTaskEnd() {
    console.log("渠道任务结束执行开始....");

    try {
        // 获取当前时间
        // const nowStr = formatLocalTimeYYMMDD();
        const nowStr = "2025-09-18 23:59:59";
        console.log("当前时间:", nowStr);

        const sql = "SELECT MAX(end_time) as end_time FROM sben_channel where is_open=?";
        const values = [1];

        // 使用 Promise 包装数据库查询
        const rows = await new Promise((resolve, reject) => {
            db.pool.getConnection(function (err, connection) {
                if (err) {
                    return reject(err);
                }
                connection.query({sql: sql, values: values}, function (err, rows) {
                    // 释放连接回连接池
                    connection.release();

                    if (err) {
                        return reject(err);
                    }

                    resolve(rows);
                });
            });
        });
        console.log("数据库查询结果为:",rows);
        if (rows.length > 0) {
            console.log("单个row为", rows[0]['end_time']);

            // 检查是否匹配当前时间（只比较日期部分）
            if (rows[0]['end_time'].split(' ')[0] === nowStr) {
                const keys = [
                    'iron_blood_war_1',
                    'iron_blood_war_2',
                    'iron_blood_war_3',
                    'iron_blood_war_4',
                    'iron_blood_war_5',
                    'iron_blood_war_6',
                    'iron_blood_war_7',
                    'iron_blood_war_8',
                ];

                // 从redis中查询出key=send_
                for (let i = 0; i < keys.length; i++) {
                    let key = 'last_' + keys[i];
                    console.info("当前key=:" + key);
                    try {
                        get_blood_war_info_async(key).then(function (result) {
                            if (result && Array.isArray(result)) {
                                history_hash_table(key, function (result) {
                                    if (result === -1) {
                                        console.log("渠道任务结束将已发奖励的变为历史的失败！！！");
                                    } else {
                                        console.log(result);
                                    }
                                });

                                console.log("渠道任务结束将已发奖励的变为历史的成功！！！", result);
                            } else {
                                console.log("当前无渠道任务结束将已发奖励的变为历史的");
                            }
                        }).catch(error =>{
                            console.error("处理key失败:", key, error);
                        });
                    } catch (error) {
                        console.error("处理key失败:", key, error);
                    }
                }
            }
        }
    } catch (error) {
        console.error("渠道任务结束执行失败:", error);
    }

    console.log("渠道任务结束执行结束....");
};

//每五分钟统计一次铁血战争名单
async function ironBloodWarStatistics() {
    console.log("铁血战争排行榜五分钟一次定时任务开始执行");
    var sql = "select a.*,b.headimgurl from (select userId,nickname,(r1_s1_hurt + r2_s1_hurt + r2_s2_hurt + r3_s1_hurt) as total_hurt from bet_statistics_daily where (r1_s1_hurt + r2_s1_hurt + r2_s2_hurt + r3_s1_hurt) >= 1000000 and updated_at BETWEEN CONCAT(CURRENT_DATE(), ' 00:00:00') AND CONCAT(CURRENT_DATE(), ' 23:59:59') order by updated_at asc) a left join (select Id,headimgurl from newuseraccounts) b on a.userId = b.Id";
    db.pool.getConnection(function (err, connection) {

        connection.query({sql: sql}, function (err, rows) {
            connection.release();
            if (err) {
                console.log("执行失败");
                console.log(err);
            } else {
                if (rows.length == 0) {
                    console.log("今日铁血战争排行榜统计名单为空");
                } else {
                    //更新名单，如果符合条件且还未写入名单的则更新到名单中
                    processRows(rows);
                }
            }
        })
    });
    console.log("铁血战争排行版五分钟一次定时任务执行完毕！！！");
}

async function processRows(rows) {
    for (let i = 0; i < rows.length; i++) {
        const row = rows[i];
        if (row.total_hurt >= ironWarHurtMap.get(8)) {
            try {
                let result = await save_blood_war_info('iron_blood_war_8', {
                    userId: row.userId.toString(),
                    nickname: row.nickname,
                    headimgurl: row.headimgurl,
                    rewardCoin: 20000,
                });
                // 根据结果处理
                if (result === 0) {
                    console.log("写入redis失败");
                } else if (result === 1) {
                    console.log("该用户已在名单");
                }
            } catch (error) {
                console.error('处理失败:', error);
            }
        }
        if (row.total_hurt >= ironWarHurtMap.get(7)) {
            try {
                const result = await save_blood_war_info('iron_blood_war_7', {
                    userId: row.userId.toString(),
                    nickname: row.nickname,
                    headimgurl: row.headimgurl,
                    rewardCoin: 20000,
                });
                // 根据结果处理
                if (result === 0) {
                    console.log("写入redis失败");
                } else if (result === 1) {
                    console.log("该用户已在名单");
                }
            } catch (error) {
                console.error('处理失败:', error);
            }
        }
        if (row.total_hurt >= ironWarHurtMap.get(6)) {
            try {
                const result = await save_blood_war_info('iron_blood_war_6', {
                    userId: row.userId.toString(),
                    nickname: row.nickname,
                    headimgurl: row.headimgurl,
                    rewardCoin: 20000,
                });
                // 根据结果处理
                if (result === 0) {
                    console.log("写入redis失败");
                } else if (result === 1) {
                    console.log("该用户已在名单");
                }
            } catch (error) {
                console.error('处理失败:', error);
            }
        }
        if (row.total_hurt >= ironWarHurtMap.get(5)) {
            try {
                const result = await save_blood_war_info('iron_blood_war_5', {
                    userId: row.userId.toString(),
                    nickname: row.nickname,
                    headimgurl: row.headimgurl,
                    rewardCoin: 20000,
                });
                // 根据结果处理
                if (result === 0) {
                    console.log("写入redis失败");
                } else if (result === 1) {
                    console.log("该用户已在名单");
                }
            } catch (error) {
                console.error('处理失败:', error);
            }
        }
        if (row.total_hurt >= ironWarHurtMap.get(4)) {
            try {
                const result = await save_blood_war_info('iron_blood_war_4', {
                    userId: row.userId.toString(),
                    nickname: row.nickname,
                    headimgurl: row.headimgurl,
                    rewardCoin: 20000,
                });
                // 根据结果处理
                if (result === 0) {
                    console.log("写入redis失败");
                } else if (result === 1) {
                    console.log("该用户已在名单");
                }
            } catch (error) {
                console.error('处理失败:', error);
            }
        }
        if (row.total_hurt >= ironWarHurtMap.get(3)) {
            try {
                const result = await save_blood_war_info('iron_blood_war_3', {
                    userId: row.userId.toString(),
                    nickname: row.nickname,
                    headimgurl: row.headimgurl,
                    rewardCoin: 20000,
                });
                // 根据结果处理
                if (result === 0) {
                    console.log("写入redis失败");
                } else if (result === 1) {
                    console.log("该用户已在名单");
                }
            } catch (error) {
                console.error('处理失败:', error);
            }
        }
        if (row.total_hurt >= ironWarHurtMap.get(2)) {
            try {
                const result = await save_blood_war_info('iron_blood_war_2', {
                    userId: row.userId.toString(),
                    nickname: row.nickname,
                    headimgurl: row.headimgurl,
                    rewardCoin: 20000,
                });
                // 根据结果处理
                if (result === 0) {
                    console.log("写入redis失败");
                } else if (result === 1) {
                    console.log("该用户已在名单");
                }
            } catch (error) {
                console.error('处理失败:', error);
            }
        }
        if (row.total_hurt >= ironWarHurtMap.get(1)) {
            try {
                const result = await save_blood_war_info('iron_blood_war_1', {
                    userId: row.userId.toString(),
                    nickname: row.nickname,
                    headimgurl: row.headimgurl,
                    rewardCoin: 20000,
                });
                // 根据结果处理
                if (result === 0) {
                    console.log("写入redis失败");
                } else if (result === 1) {
                    console.log("该用户已在名单");
                }
            } catch (error) {
                console.error('处理失败:', error);
            }
        }
    }
}


// const job1 = schedule.scheduleJob('*/1 * * * *', channelTaskEnd);//每天0点10分执行，渠道任务结束将已发奖励的变为历史的
const job2 = schedule.scheduleJob('*/1 * * * *', ironBloodWarStatistics);//每天0点10分执行，渠道任务结束将已发奖励的变为历史的